package com.quick.send.contact.activity;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class SendSMSActivity extends QuickActivity {

	private Boolean isSend;
	private BroadcastReceiver broadcastReceiverSent;
	private BroadcastReceiver broadcastReceiverDelivered;
	/** The view to show the ad. */
	private AdView adView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_sms_activity);
		// Create an ad.
		adView = (AdView) this.findViewById(R.id.adView);
		if (isNetworkConnected()) {
			AdRequest adRequest = new AdRequest.Builder().build();
			adView.loadAd(adRequest);
		} else {
			adView.setVisibility(View.GONE);
		}
		//
		this.handleDataBinding();
		this.handleAction();
		// Initialize flag for send sms or exit application
		setIsSend(true);

	}

	private void handleDataBinding() {

		SharedPreferences sharedPreferences = getSharedPreferences();
		// Get selected contacts
		String selectedContacts = sharedPreferences.getString(
				PREFS_SELECTED_CONTACTS,
				getResources().getString(R.string.no_phone_number));
		// Get selected receiver
		String selectedReceiver = sharedPreferences.getString(
				PREFS_RECEIVER_CONTACTS,
				getResources().getString(R.string.no_phone_number));

		EditText editTextContent = (EditText) findViewById(R.id.editTextContent);
		EditText editTextTo = (EditText) findViewById(R.id.editTextTo);

		editTextTo.setText(selectedReceiver);
		editTextContent.setText(selectedContacts);
	}

	private void handleAction() {
		// Handle button cancel and done
		ImageView imgBack = (ImageView) findViewById(R.id.imgBackToSelectReceiver);
		imgBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Back to previous screen
				startActivity(new Intent(SendSMSActivity.this,
						SelectReceiversActivity.class));
				// finish this activity
				finish();

			}
		});

		ImageView imgSend = (ImageView) findViewById(R.id.imgSend);
		imgSend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (isSend) {
					Boolean isSuccess = prepareSMSAndSend();
					if (isSuccess) {
						// Change send button to exit
						setIsSend(false);
					}
				} else {
					clearSharedPreferences();
					finish();
				}

			}
		});

	}

	private Boolean prepareSMSAndSend() {

		Boolean returnStatus = false;

		try {

			EditText editTextTo = (EditText) findViewById(R.id.editTextTo);
			EditText editTextContent = (EditText) findViewById(R.id.editTextContent);
			// Get to and content
			String sendSmsTo = editTextTo.getText().toString();
			String smsContent = editTextContent.getText().toString();
			if (sendSmsTo.trim().equals("")) {
				Toast.makeText(getBaseContext(),
						getResources().getString(R.string.send_to_empty),
						Toast.LENGTH_SHORT).show();
				editTextTo.requestFocus();
				return returnStatus;
			}
			if (smsContent.trim().equals("")) {
				Toast.makeText(getBaseContext(),
						getResources().getString(R.string.send_content_empty),
						Toast.LENGTH_SHORT).show();
				editTextContent.requestFocus();
				return returnStatus;
			}
			// Send to multiple number
			String[] phoneNumbers = sendSmsTo.split(";");
			PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
					new Intent(SENT), 0);

			PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
					new Intent(DELIVERED), 0);
			SmsManager sms = SmsManager.getDefault();
			for (String mobileNumber : phoneNumbers) {
				sms.sendTextMessage(mobileNumber, null, smsContent, sentPI,
						deliveredPI);
				registerReceiverSMSToSaveHistory(mobileNumber, smsContent);
			}
			returnStatus = true;

		} catch (Exception e) {
			Toast.makeText(getBaseContext(),
					getResources().getString(R.string.send_fail),
					Toast.LENGTH_LONG).show();
		}

		return returnStatus;

	}

	private void unRegisterReceiverSMS() {
		if (broadcastReceiverSent != null) {
			unregisterReceiver(broadcastReceiverSent);
		}
		if (broadcastReceiverDelivered != null) {
			unregisterReceiver(broadcastReceiverDelivered);
		}
	}

	private void registerReceiverSMSToSaveHistory(final String phoneNumber,
			final String smsContent) {

		try {
			
			if (broadcastReceiverSent == null) {
				broadcastReceiverSent = new BroadcastReceiver() {

					@Override
					public void onReceive(Context context, Intent intent) {
						switch (getResultCode()) {
						case Activity.RESULT_OK:
							ContentValues values = new ContentValues();
							values.put("address", phoneNumber);
							values.put("body", smsContent);
							getContentResolver().insert(
									Uri.parse("content://sms/sent"), values);
							Toast.makeText(
									getBaseContext(),
									getResources().getString(
											R.string.send_success)
											+ ": "
											+ values.get("address").toString(),
									Toast.LENGTH_SHORT).show();
							break;

						case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
							Toast.makeText(
									getBaseContext(),
									getResources().getString(
											R.string.generic_failure),
									Toast.LENGTH_SHORT).show();
							break;
						case SmsManager.RESULT_ERROR_NO_SERVICE:
							Toast.makeText(
									getBaseContext(),
									getResources().getString(
											R.string.no_service),
									Toast.LENGTH_SHORT).show();
							break;
						case SmsManager.RESULT_ERROR_NULL_PDU:
							Toast.makeText(
									getBaseContext(),
									getResources().getString(R.string.null_PDU),
									Toast.LENGTH_SHORT).show();
							break;
						case SmsManager.RESULT_ERROR_RADIO_OFF:
							Toast.makeText(
									getBaseContext(),
									getResources()
											.getString(R.string.radio_off),
									Toast.LENGTH_SHORT).show();
							break;
						}
					}
				};
			}
			registerReceiver(broadcastReceiverSent, new IntentFilter(SENT));
			// ---when the SMS has been delivered---
			if (broadcastReceiverDelivered == null) {
				broadcastReceiverDelivered = new BroadcastReceiver() {
					@Override
					public void onReceive(Context arg0, Intent arg1) {
						switch (getResultCode()) {
						case Activity.RESULT_OK:
							Toast.makeText(
									getBaseContext(),
									getResources().getString(
											R.string.sms_delivered),
									Toast.LENGTH_SHORT).show();
							break;
						case Activity.RESULT_CANCELED:
							Toast.makeText(
									getBaseContext(),
									getResources().getString(
											R.string.sms_not_delivered),
									Toast.LENGTH_SHORT).show();
							break;
						}
					}
				};
			}
			registerReceiver(broadcastReceiverDelivered, new IntentFilter(
					DELIVERED));
			
		} catch (Exception e) {
			Log.e(DEBUG_TAG, "Failed to registerReceiverSMSToSaveHistory", e);
		}
	}

	@SuppressWarnings("deprecation")
	public void setIsSend(Boolean isSend) {
		this.isSend = isSend;
		ImageView imgSend = (ImageView) findViewById(R.id.imgSend);
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (this.isSend) {

			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				imgSend.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.img_send_custom));
			} else {
				imgSend.setBackground(getResources().getDrawable(
						R.drawable.img_send_custom));
			}

		} else {

			if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
				imgSend.setBackgroundDrawable(getResources().getDrawable(
						R.drawable.img_exit_custom));
			} else {
				imgSend.setBackground(getResources().getDrawable(
						R.drawable.img_exit_custom));
			}
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		clearSharedPreferences();
	}

	@Override
	public void onResume() {
		super.onResume();
		if (adView != null) {
			adView.resume();
		}
	}

	@Override
	public void onPause() {
		if (adView != null) {
			adView.pause();
		}
		super.onPause();
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
		try {
			unRegisterReceiverSMS();
		} catch (Exception e) {
			Log.e(DEBUG_TAG, "Failed to unregister receiver", e);
		}
	}

}
